package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.common.BaseContext;
import com.itheima.dao.OrdersDao;
import com.itheima.exception.CustomException;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/2/25
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 下单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //0.开启事务（涉及到orders订单表 、order_detail订单明细表两张表的更新操作）
        //1.获取当前登录的用户id
        Long userId = BaseContext.getCurrentId();

        //2.查询用户表，得到用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("该用户不存在！");
        }

        //3.构造订单明细数据 List<OrderDetail>
        List<OrderDetail> orderDetailList = new ArrayList<>();

        //3.1 查询购物车数据，根据当前用户id查，得到购物车列表
        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(cartWrapper);
        if (cartList.isEmpty()) {
            throw new CustomException("请先添加商品到购物车！");
        }

        //3.2 循环购物车列表，将购物车数据拷贝给OrderDetail
        //使用工具类，生成订单id，底层使用的是雪花策略
        long orderId = IdWorker.getId();
        BigDecimal sumAmount = new BigDecimal(0);
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //3.3 设置订单id
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            //3.4 计算总金额 (累加每个商品的单价*数量)
            sumAmount = sumAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //4.构造订单数据 Orders
        //4.1 补齐字段
        orders.setId(orderId);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());

        //根据地址id查询地址表
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        +(addressBook.getCityName() == null ? "" :addressBook.getCityName())
                        +(addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        +(addressBook.getDetail() == null ? "": addressBook.getDetail()));

        //4.2 设置总金额
        orders.setAmount(sumAmount);

        //5.调用orderDetailservice的保存方法，将订单明细数据保存到order_detail表中
        orderDetailService.saveBatch(orderDetailList);

        //6.调用自身的保存方法，将订单数据保存到orders表中
        this.save(orders);

        //7.清空购物车(清空当前用户下的购物车)
        shoppingCartService.remove(cartWrapper);
    }
    
    
    /**
     * 再来一单
     * @param orders
     */
    @Override
    public void again(Orders orders) {
    
       
        //先获取到订单的主键id，用于获取到整条数据
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, id);
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        // 获取该订单对应的所有的订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        // 通过用户id把原来的购物车给清空
        shoppingCartService.remove(wrapper);
        
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            // 把从order表中和order_details表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                // 如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                // 添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
    
        // 把携带数据的购物车批量插入购物车表
        shoppingCartService.saveBatch(shoppingCartList);
    }
}
